﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Xml.Serialization;
using System.IO;
using System.Text.RegularExpressions;

namespace Main
{
    public partial class Main : Form
    {
        List<DataRow> DataRowList = new List<DataRow>();
        Thread InThread;
        SICOMModbus.ModbusRTUSlave MTS;
        SICOMModbus.ModbusTcpSlave MTCP = new SICOMModbus.ModbusTcpSlave();

        bool started = false;
        bool error = false;
        public Main()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        void M_TransactionCompleteEvent(SICOMModbus.ModbusTCPTransaction Transaction)
        {
            error = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {

            SICOMModbus.ModbusRTUSlave MTS = new SICOMModbus.ModbusRTUSlave("COM1", 9600, 3000, 3000);

            byte[] bb = MTS.ReadHoldingRegisters(0, 1, 1);

            for (int j = 0; j < bb.Length; j++)
            {
                Console.Write("|" + bb[j].ToString());
            }
        }

        void SaveDataArrayConfig()
        {
            List<DataRow> listTemp = new List<DataRow>();
            for (int i = 0; i < dGVDataArrayConfig.Rows.Count; i++)
            {
                DataRow dr = new DataRow();
                //输入功能码
                if (string.IsNullOrEmpty(dGVDataArrayConfig.Rows[i].Cells["InFunctionCode"].EditedFormattedValue.ToString()))
                {
                    //dGVDataArrayConfig.Rows[i].Cells[0].Style.BackColor = Color.Red;
                    continue;
                }
                else
                {
                    dGVDataArrayConfig.Rows[i].Cells["InFunctionCode"].Style.BackColor = Color.FromArgb(192, 192, 255);
                    dr.InFunctionCode = Convert.ToInt16(dGVDataArrayConfig.Rows[i].Cells["InFunctionCode"].EditedFormattedValue);
                }
                //输入地址
                if (string.IsNullOrEmpty(dGVDataArrayConfig.Rows[i].Cells["InAddress"].EditedFormattedValue.ToString()))
                {
                    dGVDataArrayConfig.Rows[i].Cells["InAddress"].Style.BackColor = Color.Red;
                    continue;
                }
                else
                {
                    dGVDataArrayConfig.Rows[i].Cells["InAddress"].Style.BackColor = Color.FromArgb(192, 192, 255);
                    dr.InAddress = Convert.ToInt16(dGVDataArrayConfig.Rows[i].Cells["InAddress"].EditedFormattedValue);

                }
                //输出地址
                if (string.IsNullOrEmpty(dGVDataArrayConfig.Rows[i].Cells["OutAddress"].EditedFormattedValue.ToString()))
                {
                    dGVDataArrayConfig.Rows[i].Cells["OutAddress"].Style.BackColor = Color.Red;
                    continue;
                }
                else
                {
                    dGVDataArrayConfig.Rows[i].Cells["OutAddress"].Style.BackColor = Color.FromArgb(255, 192, 192);
                    dr.OutAddress = Convert.ToInt16(dGVDataArrayConfig.Rows[i].Cells["OutAddress"].EditedFormattedValue);
                }
                //输出功能码
                if (string.IsNullOrEmpty(dGVDataArrayConfig.Rows[i].Cells["OutFunctionCode"].EditedFormattedValue.ToString()))
                {
                    dGVDataArrayConfig.Rows[i].Cells["OutFunctionCode"].Style.BackColor = Color.Red;
                    continue;
                }
                else
                {
                    dGVDataArrayConfig.Rows[i].Cells["OutFunctionCode"].Style.BackColor = Color.FromArgb(255, 192, 192);
                    dr.OutFunctionCode = Convert.ToInt16(dGVDataArrayConfig.Rows[i].Cells["OutFunctionCode"].EditedFormattedValue);
                }



                dr.Name = dGVDataArrayConfig.Rows[i].Cells["Name"].EditedFormattedValue.ToString();


                if (string.IsNullOrEmpty(dGVDataArrayConfig.Rows[i].Cells["ID"].EditedFormattedValue.ToString()) ||
                    dGVDataArrayConfig.Rows[i].Cells["ID"].EditedFormattedValue.ToString() ==
                    "00000000-0000-0000-0000-000000000000"
                    )
                {
                    dr.ID = Guid.NewGuid();
                }
                else
                {
                    dr.ID = new Guid(dGVDataArrayConfig.Rows[i].Cells["ID"].EditedFormattedValue.ToString());
                }

                listTemp.Add(dr);
            }
            DataRowList = listTemp;
        }
        private void btnSaveDataArrayConfig_Click(object sender, EventArgs e)
        {
            SaveDataArrayConfig();
            XmlSerializer xs = new XmlSerializer(typeof(List<DataRow>));
            Stream stream = new FileStream("DataRow.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            xs.Serialize(stream, DataRowList);
            stream.Close();

        }

        private void dGVDataArrayConfig_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {

        }

        private void btnStartIn_Click(object sender, EventArgs e)
        {

            if (!checkInput.IsIP(txtServerIP.Text, txtServerIP, errorProvider1))
            {
                return;
            }

            try
            {
                if (!started)
                {
                    MTS = new SICOMModbus.ModbusRTUSlave(comboBoxPortName.Text, Convert.ToInt32(comboBoxBaudRate.Text), 3000, 3000);
                    MTCP.TransactionCompleteEvent += new SICOMModbus.ModbusTcpSlave.TransactionCompleteDelegate(M_TransactionCompleteEvent);
                    MTCP.SendErroEvent += new SICOMModbus.ModbusTcpSlave.SendErroHandler(MTCP_SendErroEvent);
                    MTCP.Connect(txtServerIP.Text);
                    ThreadStart ts = new ThreadStart(getData);
                    InThread = new Thread(ts);
                    started = true;
                    InThread.Start();

                }
                else
                {
                    started = false;
                    MTS.ClosePort();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

        void MTCP_SendErroEvent()
        {
            error = true;

        }
        private void getData()
        {
            while (true && started)
            {
                for (int i = 0; i < DataRowList.Count && started; i++)
                {
                    //byte[] bb = MTS.ReadHoldingRegisters((Int16)(DataRowList[i].InAddress - 1), 1, 1);
                    //DataRowList[i].InValue = (Int16)((bb[3] << 8) + bb[4]);
                    DataRowList[i].InValue = (Int16)33; 
                    MTCP.WriteSingleRegister((Int16)(DataRowList[i].OutAddress - 1), DataRowList[i].InValue, DataRowList[i].InAddress);
                }
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(List<DataRow>));
                Stream stream = new FileStream("DataRow.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                DataRowList = (List<DataRow>)xs.Deserialize(stream);
                stream.Close();
            }
            catch
            {

            }
            FillDataGridView();

        }

        private void ToolStripMenuItemAddNewRow_Click(object sender, EventArgs e)
        {
            dGVDataArrayConfig.DataSource = null;
            DataRow dr = new DataRow();
            dr.ID = Guid.NewGuid();
            DataRowList.Add(dr);
            FillDataGridView();

        }

        private void FillDataGridView()
        {
            try
            {

                if (DataRowList.Count < 1)
                {
                    DataRow dr = null;
                    DataRowList.Add(dr);
                }
                dGVDataArrayConfig.DataSource = null;
                dGVDataArrayConfig.DataSource = DataRowList;

                dGVDataArrayConfig.Columns["Name"].HeaderText = "数据名称";
                dGVDataArrayConfig.Columns["Name"].Width = 175;

                dGVDataArrayConfig.Columns["InFunctionCode"].HeaderText = "输入参数";
                dGVDataArrayConfig.Columns["InFunctionCode"].DefaultCellStyle.BackColor = Color.FromArgb(192, 192, 255);

                dGVDataArrayConfig.Columns["InAddress"].HeaderText = "输入地址";
                dGVDataArrayConfig.Columns["InAddress"].DefaultCellStyle.BackColor = Color.FromArgb(192, 192, 255);

                dGVDataArrayConfig.Columns["OutAddress"].HeaderText = "输出地址";
                dGVDataArrayConfig.Columns["OutAddress"].DefaultCellStyle.BackColor = Color.FromArgb(255, 192, 192);

                dGVDataArrayConfig.Columns["OutFunctionCode"].HeaderText = "输出参数";
                dGVDataArrayConfig.Columns["OutFunctionCode"].DefaultCellStyle.BackColor = Color.FromArgb(255, 192, 192);


                dGVDataArrayConfig.Columns["InValue"].Visible = false;
                dGVDataArrayConfig.Columns["ID"].Visible = false;
                dGVDataArrayConfig.CurrentCell = dGVDataArrayConfig.Rows[dGVDataArrayConfig.Rows.Count - 1].Cells["InFunctionCode"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ToolStripMenuItemDeleteRow_Click(object sender, EventArgs e)
        {
            int Index = -1;
            for (int i = 0; i < DataRowList.Count; i++)
            {
                if (DataRowList[i].ID.ToString() == dGVDataArrayConfig.Rows[dGVDataArrayConfig.CurrentRow.Index].Cells["ID"].EditedFormattedValue.ToString())
                {
                    Index = i;
                    break;
                }
            }
            if (Index != -1)
            {
                DataRowList.RemoveAt(Index);
            }
            FillDataGridView();
        }

        private void timerServer_Tick(object sender, EventArgs e)
        {
            if (started)
            {
                btnStartIn.Text = "停  止";
                btnStartIn.BackColor = Color.GreenYellow;
                if (error)
                {
                    labError.Visible = true;
                    labError.Text = DateTime.Now.ToString() + "TCP/IP网络出现异常，\r\n请检查连接和ModbusTCPServer";
                    if (labError.ForeColor == Color.Red)
                    {
                        labError.ForeColor = Color.Yellow;
                    }
                    else
                    {
                        labError.ForeColor = Color.Red;

                    }

                    try
                    {
                        if (started)
                        {
                            MTCP.TransactionCompleteEvent += new SICOMModbus.ModbusTcpSlave.TransactionCompleteDelegate(M_TransactionCompleteEvent);
                            MTCP.SendErroEvent += new SICOMModbus.ModbusTcpSlave.SendErroHandler(MTCP_SendErroEvent);
                            MTCP.Connect(txtServerIP.Text);

                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                {
                    labError.Text = "";
                }
            }
            else
            {
                btnStartIn.Text = "开  始";
                btnStartIn.BackColor = Color.Red;
                labError.Text = "";

            }

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;

        }

        private void Main_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }

        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                notifyIcon1.BalloonTipTitle = "数据转换服务器";
                notifyIcon1.BalloonTipText = "程序还在继续运行......" + "\r\n" + "单击托盘图标还原窗口."+ "\r\n" +"如需关闭请右键单击图标";
                notifyIcon1.ShowBalloonTip(2000);
            }

        }

        private void ToolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            started = false;
            Thread.Sleep(600);
            this.Dispose();
        }

        private void ToolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void ToolStripMenuItemMin_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Help.htm");
        }



    }
}
